<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">发消息</button>
    <button id="btn2">关闭连接</button>
  </body>
  <script>
    //1.通过websocket与服务器建立连接
    const ws = new WebSocket('wss://javascript.info/article/websocket/demo/hello')
    //2.监听连接成功
    ws.onopen = () => {
      console.log('连接成功')
    }
    //3.如何给服务器发送消息 ws.onmessage 事件
    document.querySelector('#btn').addEventListener('click', function () {
      ws.send('你好，服务器')
    })
    //4.如果接收服务器的消息 ws.onmessage事件
    ws.onmessage = (event) => {
      console.log(event.data)
    }
    //5.如果关闭  ws.close()方法
    document.querySelector('#btn2').addEventListener('click', function () {
      ws.close()
    })
    //6.监听通信关闭  ws.onclose 事件
    ws.onclose = () => {
      console.log('连接已经关闭')
    }
  </script>
</html>
